import requests
import threading
import time
import random

"""
这个版本是可用的达到目标的《
超出4个并发则直接返回，服务需要排队
"""

# FastAPI 服务的地址
BASE_URL = "http://127.0.0.1:8002/api/v1/"

# 测试消息
TEST_MESSAGE = {"message": "Hello world", "api_key": "fastgpt-o4xhIPNCJnxOCIjdhXszuqW8E8NZm00BeSxEe6269jOr74jKF2BGq3x1Egnd", "stream": True}

# 测试线程数量
NUM_THREADS = 10

# 用于记录每个线程的响应结果
responses = []

def send_request(thread_id):
    sleep_int = random.randint(1, 10)
    time.sleep(sleep_int)
    print("thread_id: {}, sleep time:{}".format(thread_id,sleep_int))
    """模拟发送请求的函数"""
    start_time = time.time()
    response = requests.post(BASE_URL, json=TEST_MESSAGE)
    end_time = time.time()
    response_time = end_time - start_time
    responses.append({
        "thread_id": thread_id,
        "status_code": response.status_code,
        "response": response.json(),
        "response_time": response_time
    })
    print(f"Thread {thread_id} finished. Response: {response.json()}, Time: {response_time:.2f}s")

def main():
    threads = []

    # 创建多个线程发送请求
    for i in range(NUM_THREADS):
        thread = threading.Thread(target=send_request, args=(i,))
        threads.append(thread)
        thread.start()

    # 等待所有线程完成
    for thread in threads:
        thread.join()

    # 打印测试结果
    for response in responses:
        print(f"Thread {response['thread_id']}:")
        print(f"  Status Code: {response['status_code']}")
        print(f"  Response: {response['response']}")
        print(f"  Response Time: {response['response_time']:.2f}s")
        print("-" * 40)

if __name__ == "__main__":
    main()